<template>
    <div class="container">
        <headerView class="header" :headerTitle="headerTitle" />
        <div class="container-content">
            <div class="content">
                <div class="content-item">
                    <div class="item-row-avatars" @click.stop="alterAvatars">
                        <div>头像</div>
                        <div class="avatars-container">
                            <div class="avatars">
                                <img :src="headImag" alt="" @click.stop="avatarsClick(headImag)">
                            </div>
                            <span>
                                <el-icon>
                                    <ArrowRight />
                                </el-icon>
                            </span>
                        </div>
                    </div>
                    <div class="item-row" v-for="(item, index) in userTab" :key="index" @click.stop="alterUser(index)">
                        <div>{{ item.rowName }}</div>
                        <div class="item-row-value">
                            <div>{{ item.rowValue }}</div>
                            <span><el-icon v-if="index == 1 || index == 2">
                                    <ArrowRight />
                                </el-icon>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <avatarsCropper class="avatar-cropper" v-if="dialogVisibleCorpper"
            v-model:dialogVisibleCorpper="dialogVisibleCorpper" @getImagValue="getImag" />
    </div>
</template>

<script setup name="AlterUser">
import { ref, onMounted } from 'vue';
import service from '@/utils/request';
import { useRoute, useRouter } from 'vue-router';
import headerView from '@/components/Header/backHeader.vue';
import { ElMessage } from 'element-plus';
import avatarsCropper from '../LoginView/avatarCropper.vue';
const route = useRoute();
const router = useRouter();
const userId = ref(route.params.id);
const headerTitle = ref({ title: '个人信息' });
const dialogVisibleCorpper = ref(false);
const avatarData = ref(null);
const headImag = ref('');
const userTab = ref([]);
const userField = ref(['Id', 'UserName', 'Phone', 'Role', 'State']);
const inteTable = () => {
    service({
        url: 'api/Users/' + userId.value,
        method: 'get',
    }).then((res) => {
        if (res != undefined) {
            userTab.value = [];
            headImag.value = res.data.headImag;
            userTab.value.push({ rowName: '用户ID', rowValue: res.data.id });
            userTab.value.push({ rowName: '用户名', rowValue: res.data.userName });
            userTab.value.push({ rowName: '电话', rowValue: res.data.phone });
            userTab.value.push({ rowName: '角色', rowValue: res.data.role });
            userTab.value.push({ rowName: '状态', rowValue: res.data.state == 0 ? '正常' : '禁用' });
        }
    });
};
const avatarsClick = (src) => {
    window.sessionStorage.setItem('headImag', src);
    router.push('/User/UserDetail/Avatars');
};
const alterUser = (index) => {
    if (index == 0 || index == 3 || index == 4) return;
    ElMessageBox.prompt('', '修改' + userTab.value[index].rowName, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: check(index),
        inputErrorMessage: '不能为空,用户名不能超过10个字符,或手机号码格式不正确',
        showClose: false,
        closeOnClickModal: false,
    }).then(({ value }) => {
        alter(userField.value[index], value);
    }).catch(() => { });
};
const alter = (fieldName, fieldValue) => {
    service({
        url: 'api/Users/' + userId.value,
        method: 'patch',
        data: {
            fieldName: fieldName, // 需要修改的字段名
            fieldValue: fieldValue // 需要修改的字段值
        }
    }).then((res) => {
        if (res != undefined) {
            ElMessage({
                message: res.data,
                type: 'success',
                plain: true,
            });
            if (res.status == 200 && fieldName == 'UserName') {
                router.push('/Login'); // 删除缓存
            } else {
                inteTable();
            }
        }
    }).catch(err => {
        ElMessage({
            message: '修改失败',
            type: 'error',
            plain: true,
        });
    });
};
const check = (index) => {
    if (index == 1) {
        return /^1[3-9]\\d{9}$/; ///^.{1,10}$/;
    } else if (index == 2) {
        return /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    }
};
const alterAvatars = () => {
    dialogVisibleCorpper.value = true;
};
// 获取用户头像
const getImag = (value) => {
    // 将base64格式的图片转换为file
    convertBase64ToFile(value);
    var formData = new FormData();
    formData.append('file', avatarData.value);
    service({
        url: 'api/Avatars/Update',
        method: 'post',
        data: formData,
    }).then(res => {
        if (res != undefined) {
            if (res.status == 200) {
                ElMessage({
                    message: '修改成功',
                    type: 'success',
                    plain: true,
                });
                headImag.value = res.data;
            }
        }
    });
};
const base64ToBlob = (base64, contentType) => {
    const byteCharacters = atob(base64);
    const byteNumbers = new Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    return new Blob([byteArray], { type: contentType });
};
const blobToFile = (blob, fileName) => {
    return new File([blob], fileName, { type: 'image/png' });
};
const convertBase64ToFile = (base64) => {
    const contentType = base64.split(',')[0].match(/:(.*?);/)[1];
    const base64Data = base64.split(',')[1];
    const blob = base64ToBlob(base64Data, contentType);
    avatarData.value = blobToFile(blob, 'image.png');
};
onMounted(() => {
    inteTable();
});
</script>
<style scoped>
.container {
    width: 100vw;
    height: 100%;
    background-color: #fff;
}

.header {
    width: 100%;
    height: 60px;
    background-color: #f5f5f5;
    box-shadow: 0px 0px 10px 5px rgba(0, 0, 0, 0.1);
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
}

.container-content {
    width: 100%;
    height: calc(100vh - 55px);
    margin-top: 55px;
}

.content {
    width: 90%;
    margin: 0 auto;
}

.content-item {
    width: 100%;
    padding-top: 20px;
}

.item-row-avatars,
.item-row {
    margin-bottom: 10px;
    width: 100%;
    height: 60px;
    line-height: 60px;
    color: #444;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #cacaca;
}

.item-row {
    height: 35px;
    line-height: 35px;
}

.avatars-container {
    display: flex;
    align-items: center;
}

.avatars {
    width: 50px;
    height: 50px;
}

.avatars img {
    width: 100%;
    height: 100%;
    border-radius: 5px;
}

.item-row-value {
    display: flex;
    align-items: center;
}

.item-row-value span {
    width: 16px;
    height: 35px;
    text-align: center;
    line-height: 39px;

}

.avatar-cropper {
    z-index: 1000;
    float: left;
    width: 100wh;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
}
</style>